<!-- 组件 -->
<template>
  <view>
    <van-field
      v-show="!props.hidden"
      :name="props.formItem?.id"
      :label="props.formItem?.title"
      :required="props.required"
      :readonly="props.readonly"
      :rules="rules"
      :input-align="FieldInputAlign.DEFAULT"
      clearable
    >
      <template #input>
        <view>
          <view class="score">
            <van-rate v-model="_value" :count="max" :allow-half="enableHalf" />
            <div style="margin-left: 10px" v-show="showScore">{{ _value }}</div>
          </view>
          <view v-if="isNotEmpty(_value) && _value === 0">{{ placeholder }}</view>
        </view>
      </template>
    </van-field>
  </view>
</template>

<script setup lang="ts">
  import { computed, watch } from 'vue';
  import { isEmpty, isNotEmpty } from '@/utils/is';
  import { evalFormual } from '@/utils/evalFormual';
  import { FieldInputAlign } from '@/enums/formEnum';
  const emits = defineEmits(['update:value', 'labelShow']);
  const props = defineProps({
    value: {
      type: Number,
      default: 0,
    },
    placeholder: {
      type: String,
      default: '请打分',
    },
    required: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    max: {
      type: Number,
      default: 5,
    },
    enableHalf: {
      type: Boolean,
      default: false,
    },
    showScore: {
      type: Boolean,
      default: true,
    },
    //隐藏组件的公共属性
    formula: {
      type: Object,
      default: () => {
        return {
          showFormula: '', //回显用，因为包含表单字段的时候会出现表单名称
          calcFormula: '', //解析用，表单名称对应为formData.fieldxxxx
        };
      },
    },
    formItem: {
      type: Object,
      default: () => {},
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    rule: {
      type: Object,
      default: () => null,
    },
    hidden: {
      type: Boolean,
      default: false,
    },
  });
  /** 计算属性：_value */
  const _value = computed({
    get() {
      return props.value;
    },
    set(val) {
      emits('update:value', val);
    },
  });
  /** 校验规则 */
  const rules = computed(() => {
    if (isEmpty(props.rule)) {
      return [];
    } else {
      return props.rule;
    }
  });

  const doFormula = () => {
    let hidden = evalFormual(props.formula.calcFormula, props.formData);
    //如果隐藏，同时也隐藏label,通知父组件去隐藏，因为label不在当前界面
    //调用父组件FormDesignRender 的方法：
    emits('labelShow', props.formItem, hidden);
  };

  watch(
    () => props.formData,
    () => {
      doFormula();
    },
    { immediate: true, deep: true },
  );
</script>

<style scoped>
  .score {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
</style>
